#!/bin/bash
 #=================== SYSTEM ===================#
  SYSTEMD="/etc/systemd/system"
  INITD="/etc/init.d"
  ETCDEF="/etc/default"
  DATABK="/home/print3D/printer_data"
  #=================== KIAUH ==================#
### sourcing all additional scripts
  KIAUH_SRCDIR="/home/print3D/kiauh"
  KIAUH_REPO="https://gitee.com/miroky/kiauh.git"
  green=$(echo -en "\e[92m")
  yellow=$(echo -en "\e[93m")
  magenta=$(echo -en "\e[35m")
  red=$(echo -en "\e[91m")
  cyan=$(echo -en "\e[96m")
  white=$(echo -en "\e[39m")
  home1="/home/print3D"
  INI_FILE="/home/print3D/kiauh.ini"
  LOGFILE="/tmp/kiauh.log"
  RESOURCES="${KIAUH_SRCDIR}/resources"
  BACKUP_DIR="/home/print3D/kiauh-backups"
  #=====================PIP======================#
  # for using official pip source, comment next line
  PIP_MIRROR="https://pypi.tuna.tsinghua.edu.cn/simple"
  #清华
  PIP3YUAN="https://pypi.tuna.tsinghua.edu.cn/simple/"
  #阿里
  #PIP3YUAN="http://mirrors.aliyun.com/pypi/simple/"
  #中国科技大学
  #PIP3YUAN="https://pypi.mirrors.ustc.edu.cn/simple/"
  #华中科技大学
  #PIP3YUAN="http://pypi.hustunique.com/simple/"
  #上海交通大学
  #PIP3YUAN="https://mirror.sjtu.edu.cn/pypi/web/simple/"
  #豆瓣
  #PIP3YUAN="http://pypi.douban.com/simple/"
  #百度
  #PIP3YUAN="https://mirror.baidu.com/pypi/simple"
  #搜狐
  #PIP3YUAN="http://mirrors.sohu.com/Python/"
  
  #=============== KLIPPERSCREEN ================#
  KLIPPERSCREEN_ENV="/home/print3D/KlipperScreen-env"
  KLIPPERSCREEN_DIR="/home/print3D/KlipperScreen"
  KLIPPERSCREEN_REPO="https://gitee.com/Neko-vecter/KlipperScreen.git"
  KLIPPERSCREEN_TXT="/home/print3D/KlipperScreen/scripts/KlipperScreen-requirements.txt"
  XSERVER="xinit xinput x11-xserver-utils xserver-xorg-input-evdev xserver-xorg-input-libinput"
  FBDEV="xserver-xorg-video-fbdev"
  PYTHON="python3-virtualenv virtualenv python3-distutils"
  PYGOBJECT="libgirepository1.0-dev gcc libcairo2-dev pkg-config python3-dev gir1.2-gtk-3.0"
  MISC="librsvg2-common libopenjp2-7 libatlas-base-dev wireless-tools libdbus-glib-1-dev autoconf"
  OPTIONAL="xserver-xorg-legacy fonts-wqy-zenhei "
  PKGLIST="libdbus-glib-1-dev autoconf fonts-wqy-zenhei "
#libmpv-dev
Red='\033[0;31m'
Green='\033[0;32m'
Cyan='\033[0;36m'
Normal='\033[0m'
#===================================================#
#============== INSTALL KLIPPERSCREEN ==============#
#===================================================#
function klipperscreen_setup() {
  # 强制删除现有KlipperScreen目录
  [[ -d ${KLIPPERSCREEN_DIR} ]] && rm -rf "${KLIPPERSCREEN_DIR}"
  # 克隆到新的KlipperScreen目录
  if ! git clone "${KLIPPERSCREEN_REPO}" "${KLIPPERSCREEN_DIR}"; then
    print_error "克隆KlipperScreen从\n ${KLIPPERSCREEN_REPO}\n 失败!"
  fi
  wget https://gitee.com/xiaoh5001/android-linux-bootstrap/raw/master/KlipperScreen-requirements.txt  -O /home/print3D/KlipperScreen/scripts/KlipperScreen-requirements.txt &>/dev/null
  status_msg "安装环境 ..."
  install_packages
  create_virtualenv "${KLIPPERSCREEN_ENV}" "${KLIPPERSCREEN_TXT}"
  modify_user
  update_x11
  install_config_KlipperScreen
  add_desktop_file
  install_systemd_service
  /home/print3D/KlipperScreen-env/bin/pip3 install PyGObject -i "${PIP3YUAN}"
  /home/print3D/KlipperScreen-env/bin/pip3 install websocket-client -i "${PIP3YUAN}"
  status_msg "KlipperScreen安装完成!"
}
function modify_user(){
  
  sudo gpasswd --add print3D dialout
  sudo gpasswd --add print3D sudo
  sudo gpasswd --add print3D tty
  sudo gpasswd --add print3D root
}
function update_x11(){
    if [ -e /etc/X11/Xwrapper.config ]
    then
       
        sed -i 's/allowed_users=console/allowed_users=anybody/g' /etc/X11/Xwrapper.config
    else
        
        echo 'allowed_users=anybody' |  tee /etc/X11/Xwrapper.config
    fi
}
function add_desktop_file(){
    DESKTOP=$(<$KLIPPERSCREEN_DIR/scripts/KlipperScreen.desktop)
    mkdir -p $HOME/.local/share/applications/
    echo "$DESKTOP" | tee $HOME/.local/share/applications/KlipperScreen.desktop > /dev/null
}
function install_config_KlipperScreen(){
    DEFAULTS_FILE=/etc/default/KlipperScreen
        status_msg  "正在安装启动配置..."
        cat > ${DEFAULTS_FILE} <<EOF
    # Configuration for /etc/init.d/KlipperScreen
    KS_USER=print3D
    KS_EXEC="/bin/bash"
    KS_ARGS=" /etc/init.d/KlipperScreensh"

EOF
    chmod +x /root/print3D/ksdelay.sh
    chmod +x /etc/init.d/KlipperScreen
    chmod +x /etc/init.d/KlipperScreensh
    chmod 777 /root/print3D/ksdelay.sh
    chmod 777 /etc/init.d/KlipperScreen
    chmod 777 /etc/init.d/KlipperScreensh

}
function install_packages()
{
    status_msg "更新包数据"
    sudo apt-get update

    status_msg "正在检查损坏的包..."
    output=$(dpkg-query -W -f='${db:Status-Abbrev} ${binary:Package}\n' | grep -E ^.[^nci])
    if [ $? -eq 0 ]; then
        status_msg "检测到损坏的包。正在尝试修复"
        sudo apt-get -f install
        output=$(dpkg-query -W -f='${db:Status-Abbrev} ${binary:Package}\n' | grep -E ^.[^nci])
        if [ $? -eq 0 ]; then
            error_msg "无法修复损坏的程序包。在安装KlipperScreen之前，必须先将其固定"
          
        fi
    else
        ok_msg "无破损包装"
    fi

    status_msg "安装KlipperScreen依赖项"
    sudo apt-get install -y $XSERVER
    if [ $? -eq 0 ]; then
        ok_msg "已安装X"
    else
        error_msg "安装X服务器依赖项失败（$XSERVER）"
       
    fi
    sudo apt-get install -y $OPTIONAL
   
    sudo apt-get install -y $FBDEV
    if [ $? -eq 0 ]; then
        ok_msg "已安装 FBdev"
    else
        error_msg "FBdev安装失败（$FBdev）"
       
    fi
    sudo apt-get install -y $PYTHON
    if [ $? -eq 0 ]; then
        ok_msg "已安装的Python依赖项"
    else
        error_msg "Python依赖项安装失败（$Python）"
        
    fi
    sudo apt-get install -y $PYGOBJECT
    if [ $? -eq 0 ]; then
        ok_msg "已安装PyGoject依赖项"
    else
        error_msg "PyGoject依赖项的安装失败（$PyGobject）"
       
    fi
    sudo apt-get install -y $MISC
    if [ $? -eq 0 ]; then
        ok_msg "已安装的杂项软件包"
    else
        error_msg "杂项软件包安装失败（$Misc）"
    fi
   #ModemManager干扰klipper通信
   #在buster上，它是作为mpv的依赖项安装的
   #它不是在靶心上发生的
    sudo systemctl mask ModemManager.service
}
    
function install_systemd_service()
{
    status_msg "安装KlipperScreen单元文件"
    sudo cp ${KLIPPERSCREEN_DIR}/scripts/KlipperScreen.service  /etc/systemd/system/ 
    sudo sed -i  's/KS_USER/${USER}/g' /etc/systemd/system/KlipperScreen.service
    sudo sed -i  's/Environment/Environment="localhost:0 \/home\/print3D\/KlipperScreen-env\/bin\/python"/g' /etc/systemd/system/KlipperScreen.service
    sudo sed -i  's/ExecStart/ExecStart="\/home\/print3D\/KlipperScreen\/screen.py -c \/home\/print3D\/printer_data\/config\/KlipperScreen.conf"/g' /etc/systemd/system/KlipperScreen.service

}

#================================================#
#============= MESSAGE FORMATTING ===============#
#================================================#
function do_action_service() {
  local services action=${1} service=${2}
  services=$(find "${SYSTEMD}" -maxdepth 1 -regextype posix-extended -regex "${SYSTEMD}/${service}(-[0-9a-zA-Z]+)?.service" | sort)

  if [[ -n ${services} ]]; then
    for service in ${services}; do
      service=$(echo "${service}" | rev | cut -d"/" -f1 | rev)
      status_msg "${action^} ${service} ..."

      if sudo systemctl "${action}" "${service}"; then
        log_info "${service}: ${action} > 成功"
        ok_msg "${action^} ${service} 成功!"
      else
        log_warning "${service}: ${action} > 失败"
        warn_msg "${action^} ${service} 失败!"
      fi
    done
  fi
}
function create_virtualenv() {
  local ljm="${1}"
  local wjm="${2}"
  status_msg "正在安装$（“python3”-V）虚拟环境..."
  [[ -d ${ljm} ]] && rm -rf "${ljm}"
  if virtualenv -p "python3" "${ljm}"; then
    "${ljm}"/bin/pip install -U pip  setuptools -i "${PIP3YUAN}"
    "${ljm}"/bin/pip install -r "${wjm}" -i "${PIP3YUAN}"
  else
    sleep 2s
    sudo dpkg --configure -a
    if virtualenv -p "python3" "${ljm}"; then
        "${ljm}"/bin/pip install -U pip  setuptools -i "${PIP3YUAN}"
        "${ljm}"/bin/pip install -r "${wjm}" -i "${PIP3YUAN}"
    else
        log_error "创建python3环境时失败"
        error_msg "virtualenv创建失败！"
    fi
  fi
}

function dependency_check(){
  local dep=( "${@}" )
  local packages
  status_msg "正在检查以下依赖项:"

  #检查是否安装了程序包，如果没有，请将其名称写入数组
  for pkg in "${dep[@]}"; do
    echo -e "${cyan}● ${pkg} ${white}"
    [[ ! $(dpkg-query -f'${Status}' --show "${pkg}" 2>/dev/null) = *\ installed ]] && \
    packages+=("${pkg}")
  done

  #如果数组不为空，则从数组安装程序包
  if (( ${#packages[@]} > 0 )); then
    status_msg "安装以下依赖项:"
    for package in "${packages[@]}"; do
      echo -e "${cyan}● ${package} ${white}"
    done
    echo

    if sudo apt-get update --allow-releaseinfo-change && sudo apt-get install "${packages[@]}" -y; then
      ok_msg "已安装依赖项!"
    else
      error_msg "安装依赖项失败!"
      return 1 # exit kiauh
    fi
  else
    ok_msg "已满足依赖项!"
    return
  fi
}

function select_msg() {
  echo -e "${white}   [➔] ${1}"
}
function status_msg() {
  echo -e "\n${magenta}###### ${1}${white}"
}
function ok_msg() {
  echo -e "${green}[✓ OK] ${1}${white}"
}
function warn_msg() {
  echo -e "${yellow}>>>>>>> ${1}${white}"
}
function error_msg() {
  echo -e "${red}>>>>>>> ${1}${white}"
}
function abort_msg() {
  echo -e "${red}<<<<<<< ${1}${white}"
}
function title_msg() {
  echo -e "${cyan}${1}${white}"
}
function print_error() {
  [[ -z ${1} ]] && return

  echo -e "${red}"
  echo -e "#=======================================================#"
  echo -e " ${1} "
  echo -e "#=======================================================#"
  echo -e "${white}"
}
function print_confirm() {
  [[ -z ${1} ]] && return

  echo -e "${green}"
  echo -e "#=======================================================#"
  echo -e " ${1} "
  echo -e "#=======================================================#"
  echo -e "${white}"
}
function log_info() {
  local message="${1}" log="${LOGFILE}"
  echo -e "$(timestamp) [INFO]: ${message}" | tr -s " " >> "${log}"
}
function log_warning() {
  local message="${1}" log="${LOGFILE}"
  echo -e "$(timestamp) [WARN]: ${message}" | tr -s " " >> "${log}"
}
function log_error() {
  local message="${1}" log="${LOGFILE}"
  echo -e "$(timestamp) [ERR]: ${message}" | tr -s " " >> "${log}"
}
function timestamp() {
  date +"[%F %T]"
}
function report_status(){
    echo -e "\n\n###### $1"
}

status_msg "安装klipperscreen！"
klipperscreen_setup
exit 0